import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:baidu_ocr_plugin/baidu_ocr_plugin.dart';
import 'package:camera/camera.dart';
import 'package:financing_wallet/home/identity_certification/widget/Calendars.dart';
import 'package:financing_wallet/home/identity_certification/widget/add_calendar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wallet_utils/base_router_config.dart';
import 'package:wallet_utils/dialog/identity_dialog.dart';
import 'package:wallet_utils/event_bus_utils.dart';
import 'package:wallet_utils/log_util.dart';
import 'package:wallet_utils/msg_event_utils.dart';
import 'package:wallet_utils/permissions_utils.dart';
import 'package:wallet_utils/regexp_utils.dart';
import 'package:wallet_utils/report_widget/base/callback/base_callback.dart';
import 'package:wallet_utils/report_widget/loading_utils.dart';
import 'package:wallet_utils/toast.dart';
import '../../mine/api/mine_api.dart';
import '../../mine/bean/aboutUsBean.dart';
import '../../mine/bean/updateImageBean.dart';
import '../api/home_api.dart';
import 'state.dart';
import 'package:path_provider/path_provider.dart';

class IdentityCertificationLogic extends GetxController {
  final IdentityCertificationState state = IdentityCertificationState();
  num? face;
  num? isShowIdCard;
  bool showContacts = false;
  num? channelAuthType;
  String? idCardFrontPath;
  String? idCardBackPath;
  bool isShowIncoming=false;
  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      isShowIncoming=Get.arguments['isShowIncoming'];
      face = Get.arguments['face'];
      showContacts = Get.arguments['showContacts'];
      isShowIdCard = Get.arguments['isShowIdCard'];
      channelAuthType = Get.arguments['channelAuthType'];
    }
    if (channelAuthType == 2) {
      state.proState = true;
      if (face == 1 && showContacts) {
        state.proText = '30%';
        state.percent = 84;
      } else if (face == 1 && !showContacts) {
        state.proText = '40%';
        state.percent = 112;
      } else if (face == 0 && showContacts) {
        state.proText = '40%';
        state.percent = 112;
      } else if (face == 0 && !showContacts) {
        state.proText = '50%';
        state.percent = 140;
      }
    }

    WidgetsFlutterBinding.ensureInitialized();
    // initAccessTokenWithAkSk();
    _initAccessToken();
  }

  //用户隐私协议选中或未选中
  void updateUserPrivary() {
    state.isAgreeUserPrivary = !state.isAgreeUserPrivary;
    update();
  }

  void initAccessTokenWithAkSk() async {
    try {
      await BaiduOcrPlugin.instance.initAccessTokenWithAkSk(state.ak, state.sk);
      state.hasGotToken = true;
    } on OCRError catch (e) {
      LogUtils.d('${e.message}');
    }
  }

  void _initAccessToken() async {
    try {
      await BaiduOcrPlugin.instance.initAccessToken();
      state.hasGotToken = true;
    } on OCRError catch (e) {
      _alert(Get.context!, '初始化错误', Text(e.message));
    }
  }

  uploadFile(File path, int type) {
    MineApi.uploadFile(
        path,
        BaseCallback(onSuccess: (map) {
          UpdateImageBean updateImageBean = UpdateImageBean.fromJson(map);
          if (updateImageBean.data != null) {
            if (type == 1) {
              idCardFrontPath = updateImageBean.data?.url;
            } else {
              idCardBackPath = updateImageBean.data?.url;
            }
            LogUtils.d('图片路径  ${idCardFrontPath}');
          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  Future<void> idCardFrontHandleStart(Uint8List imageBytes) async {
    // _alert(Get.context!, '图片', Image.memory(imageBytes));
    LoadingUtils.showLoading(Get.context!, isCanBack: false);
    state.idCardFront = true;
    state.idCardFrontImageBytes = imageBytes;
    File file = await saveImage(imageBytes);
    LogUtils.d('图片----------${file}');
    uploadFile(file, 1);
  }

  //将回调拿到的Uint8List格式的图片转换为File格式
  Future<File> saveImage(Uint8List imageByte) async {
    //获取临时目录
    var tempDir = await getTemporaryDirectory();
    //生成file文件格式
    var file = await File('${tempDir.path}/image_${DateTime.now().millisecond}.jpg').create();
    //转成file文件
    file.writeAsBytesSync(imageByte);
    print("${file.path}");
    return file;
  }

  Future<void> idCardBackHandleStart(Uint8List imageBytes) async {
    // _alert(Get.context!, '图片', Image.memory(imageBytes));
    LoadingUtils.showLoading(Get.context!, isCanBack: false);
    state.idCardBack = true;
    state.idCardBackImageBytes = imageBytes;
    File file = await saveImage(imageBytes);
    uploadFile(file, 2);
  }

  //身份面结果
  void idCardFrontHandleJsonRes(String jsonRes) {
    final jsonResponse = json.decode(jsonRes);
    LogUtils.d(jsonRes);
    String name = jsonResponse['words_result']['姓名']['words'];
    String number = jsonResponse['words_result']['公民身份号码']['words'];
    String place = jsonResponse['words_result']['住址']['words'];
    String nation = jsonResponse['words_result']['民族']['words'];

    state.nameController.text = name;
    state.cardController.text = number;
    state.placeController.text = place;
    state.nationController.text = nation;
    state.proState = true;
    proCount(state.timeController.text);
    Get.back();
    update();
    // _alert(Get.context!, '识别结果', Text(jsonRes));
  }

  void proCount(String content) {
    if (channelAuthType == 1) {
      if (face == 1 && showContacts) {
        if (content.isNotEmpty) {
          state.proText = '30%';
          state.percent = 84;
        } else {
          state.proText = '15%';
          state.percent = 42;
        }
      } else {
        if (content.isNotEmpty) {
          state.proText = '50%';
          state.percent = 140;
        } else {
          state.proText = '25%';
          state.percent = 70;
        }
      }
    } else {
      if (face == 1 && showContacts) {
        if (content.isNotEmpty) {
          state.proText = '60%';
          state.percent = 168;
        } else {
          state.proText = '45%';
          state.percent = 126;
        }
      } else if (face == 1 && !showContacts) {
        if (content.isNotEmpty) {
          state.proText = '90%';
          state.percent = 252;
        } else {
          state.proText = '65%';
          state.percent = 182;
        }
      } else if (face == 0 && showContacts) {
        if (content.isNotEmpty) {
          state.proText = '90%';
          state.percent = 252;
        } else {
          state.proText = '65%';
          state.percent = 182;
        }
      } else if (face == 0 && !showContacts) {
        state.proText = '50%';
        state.percent = 140;
        if (content.isNotEmpty) {
          state.proText = '100%';
          state.percent = 280;
        } else {
          state.proText = '75%';
          state.percent = 210;
        }
      }
    }
  }

  //身份背面结果
  void idCardBackHandleJsonRes(String jsonRes) {
    final jsonResponse = json.decode(jsonRes);
    LogUtils.d(jsonRes);
    String startTime = jsonResponse['words_result']['签发日期']['words'];
    String endTime = jsonResponse['words_result']['失效日期']['words'];
    String issuingAuth = jsonResponse['words_result']['签发机关']['words'];

    // LogUtils.d('姓名-----------------$name');
    state.timeController.text = startTime + '-' + endTime;
    state.proState = true;
    state.issuingAuthController.text = issuingAuth;
    proCount(state.nameController.text);
    // if (state.nameController.text.isNotEmpty && state.cardController.text.isNotEmpty && state.placeController.text.isNotEmpty) {
    //   state.proText = '50%';
    //   state.percent = 280 / 2;
    // } else {
    //   state.proText = '25%';
    //   state.percent = 280 / 4;
    // }

    Get.back();
    update();
    // _alert(Get.context!, '识别结果', Text(jsonRes));
  }

  void handleOcrError(OCRError ocrError) {
    LogUtils.d('111111111111111111');
    _alert(Get.context!, '识别错误', Text(ocrError.message));
  }

  bool checkTokenStatus() {
    if (!state.hasGotToken) ToastUtils.showToast('token还未成功获取');

    return state.hasGotToken;
  }

  void _alert(BuildContext context, String title, [Widget? content]) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(title),
          content: SingleChildScrollView(child: content),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('确定'),
            )
          ],
        );
      },
    );
  }

  void submit() {
    if (idCardFrontPath!.isEmpty) {
      ToastUtils.showToast('人像照片不能为空');
    } else if (idCardBackPath!.isEmpty) {
      ToastUtils.showToast('国徽页照片不能为空');
    } else if (state.nameController.text.isEmpty) {
      ToastUtils.showToast('姓名不能为空');
    } else if (state.cardController.text.isEmpty) {
      ToastUtils.showToast('身份证号不能为空');
    } else if (state.timeController.text.isEmpty) {
      ToastUtils.showToast('身份证有效期不能为空');
    } else if (state.placeController.text.isEmpty) {
      ToastUtils.showToast('籍贯不能为空');
    }  else if (state.issuingAuthController.text.isEmpty) {
      ToastUtils.showToast('发证机关不能为空');
    } else if (state.nationController.text.isEmpty) {
      ToastUtils.showToast('民族不能为空');
    }else if (!state.isAgreeUserPrivary) {
      ToastUtils.showToast('请先勾选同意授权书');
    }else if (!RegExpUtils.regExpMatchIDCard(state.cardController.text)) {
      ToastUtils.showToast('请输入正确的身份证号');
    } else {
      LoadingUtils.showLoading(Get.context!, isCanBack: false);
      if (channelAuthType == 1) {
        authIdCard();
      } else {
        authIdCardAndPush();
      }
    }
  }

  //提交用户身份证信息1  前置
  void authIdCard() async {
    HomeApi.authIdCard(
        state.nameController.text,
        state.cardController.text,
        idCardFrontPath!,
        idCardBackPath!,
        state.timeController.text,
        state.placeController.text,
        state.issuingAuthController.text,
        state.nationController.text,
        BaseCallback(onSuccess: (map) async {
          Get.back();
          //基础信息
          Get.toNamed(BaseRouterConfig.basicInfo, arguments: {
            'face': face,
            'showContacts': showContacts,
            'isShowIdCard': isShowIdCard,
            'channelAuthType': channelAuthType,
          });
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            Get.back();
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  //提交用户身份证信息1  后置
  void authIdCardAndPush() async {
    HomeApi.authIdCardAndPush(
        state.nameController.text,
        state.cardController.text,
        idCardFrontPath!,
        idCardBackPath!,
        state.timeController.text,
        state.placeController.text,
        state.issuingAuthController.text,
        state.nationController.text,
        BaseCallback(onSuccess: (map) async {
          Get.back();
          if (showContacts) {
            //联系人
            Get.toNamed(BaseRouterConfig.contactPerson, arguments: {
              'isShowIncoming':isShowIncoming,
              'face': face,
              'isShowIdCard': isShowIdCard,
              'channelAuthType': channelAuthType,
            });
          } else {
            if (face == 1) {
              WidgetsFlutterBinding.ensureInitialized();
              state.cameras = await availableCameras();

              /// 获取设备摄像头，默认0:后置 1:前置
              state.firstCamera = state.cameras!.first;
              Get.toNamed(BaseRouterConfig.faceRecognition, arguments: {
                'isShowIncoming':isShowIncoming,
                'camera': state.cameras,
              });
            } else {
              if(isShowIncoming){
                Get.toNamed(BaseRouterConfig.result);
              }else{
                Get.toNamed(BaseRouterConfig.auditRejection);
              }
            }
          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            Get.back();
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  void backPage() {
    infoDialog();
  }

  void infoDialog() {
    showDialog(
        context: Get.context!,
        builder: (context) {
          return IdentityDialog(
            "",
            title: 'ocr日历提醒弹窗',
            yesStr: '确认提醒时间',
            submitCallback: (name) async {
              Calendars calendars;
              var startNow = DateTime.now();
              var endNow = DateTime.now();
              if (name == '1小时后') {
                endNow = startNow.add(const Duration(hours: 1));
              } else if (name == '2小时后') {
                endNow = startNow.add(const Duration(hours: 2));
              } else {
                endNow = startNow.add(const Duration(hours: 24));
              }
              // createEvent(calendars);
              calendars = Calendars(startNow, endNow, '身份证', '身份证', [5], '1', 1);
              bool isGranted = await PermissionsUtils.request(PermissionType.calendar, Get.context, isShowRejectDialog: false);
              if (isGranted) {
                AddCalendar.createEvent(calendars);
                Get.back();
                if (channelAuthType == 2) {
                  EventBusUtils.getInstance().fire(MsgEventBusUtils(MsgEventBusUtils.upHomeStatus, value: false));
                  Get.until((route) => (route.settings.name == BaseRouterConfig.main));
                } else {
                  Get.back();
                }
              }
            },
            backCallback: () {
              Get.back();
              if (channelAuthType == 2) {
                EventBusUtils.getInstance().fire(MsgEventBusUtils(MsgEventBusUtils.upHomeStatus, value: false));
                Get.until((route) => (route.settings.name == BaseRouterConfig.main));
              } else {
                Get.back();
              }
            },
          );
        });
  }

  //信用授权书
  getUserInfo(int type) {
    MineApi.getHTML(
        type,
        BaseCallback(onSuccess: (map) {
          AboutUsBean aboutUsBean = AboutUsBean.fromJson(map);
          if (aboutUsBean.data != null) {
            String? name = aboutUsBean.data?.name;
            String? content = aboutUsBean.data?.content;
            Get.toNamed(BaseRouterConfig.agreement, arguments: {'name': name, 'content': content});
          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }
}
